﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace AF_QRCode
{
    public class QRCode
    {
        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="text">要生成的文本</param>
        /// <param name="width">二维码图片宽</param>
        /// <param name="height">二维码图片高</param>
        /// <returns></returns>
        public Image GetQRCode(string text, int width, int height)
        {
            DotNetBarcode dnb = new DotNetBarcode();
            dnb.Type = DotNetBarcode.Types.QRCode;
            dnb.PrintCheckDigitChar = true;
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(width, height);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            dnb.WriteBar(text, 0, 0, width, height, g);
            return bitmap;

        }
        /// <summary>
        /// 获取二维码 带LOGO
        /// </summary>
        /// <param name="text">要生成的文本</param>
        /// <param name="width">二维码图片宽</param>
        /// <param name="height">二维码图片高</param>
        /// <param name="logo">中间显示的图片</param>
        /// <returns></returns>
        public Image GetQRCode(string text, int width, int height, Image logo)
        {
            DotNetBarcode dnb = new DotNetBarcode();
            dnb.Type = DotNetBarcode.Types.QRCode;
            dnb.PrintCheckDigitChar = true;
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(width, height);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            dnb.WriteBar(text, 0, 0, width, height, g);

            int logoPercent = 5;//logo为二维码图的几分之一
            g.DrawImage(logo, new System.Drawing.Rectangle(bitmap.Width / 2 - bitmap.Width / logoPercent / 2, bitmap.Height / 2 - bitmap.Height / logoPercent / 2, bitmap.Width / logoPercent, bitmap.Height / logoPercent), new System.Drawing.Rectangle(0, 0, logo.Width, logo.Height), System.Drawing.GraphicsUnit.Pixel);
            return bitmap;
        }
    }
}
